package com.zsummer.baikal.common.config.security;

import com.alibaba.fastjson.JSON;
import com.zsummer.baikal.common.constant.HttpStatus;
import com.zsummer.baikal.common.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证授权异常处理器
 * @author zsummer
 * @since 2021/7/30
 */
@Component
@Slf4j
public class AuthFailureEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        R<Object> result;
        if (authException instanceof UsernameNotFoundException) {
            result = R.restResult(null, HttpStatus.UNAUTHORIZED, authException.getMessage());
        }
        else if (authException instanceof BadCredentialsException){
            result = R.restResult(null, HttpStatus.UNAUTHORIZED, "密码错误");
        }
        else if (authException instanceof InsufficientAuthenticationException){
            result = R.restResult(null, HttpStatus.UNAUTHORIZED, "未登录");
        }
        else {
            result = R.restResult(null, HttpStatus.UNAUTHORIZED, authException.getClass().getName());
        }
        response.getWriter().write(JSON.toJSONString(result));
        log.error("认证授权失败", authException);
    }
}
